using System;
using System.Reflection;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Configuration;
using System.Collections;
using System.Threading;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using ACM.cmsarea08;
using ACM.cmsarea08.mainconfiguration;



namespace ACM.cmsarea08.Core {
	public class EditorTemplate :  IHttpAsyncHandler { //IHttpAsyncHandler IHttpHandler
/*
<?xml version="1.0" encoding="UTF-8"?>
<JoackVersion>
	<Version>123</Version>
	<Assemblies>
			<Assembly>
				<name>123</name>
				<version>123</version>
			</Assembly>
	</Assemblies>

</JoackVersion>
*/		
		
       public bool IsReusable { get { return true; } }
       const string assemblyS = "<Assembly>"+
				"<name>{0}</name>"+
				"<version>{1}</version>"+
			"</Assembly>\n\r";
      public void ProcessRequest(System.Web.HttpContext contesto)
        {
			// non usato
        }
		
	  public IAsyncResult BeginProcessRequest(HttpContext ctx, AsyncCallback cb, object obj)
	  {
	    AsyncEditorTemplateState reqState = new AsyncEditorTemplateState(ctx, cb, obj);
	    AsyncEditorTemplateRequest ar = new AsyncEditorTemplateRequest(reqState);
	    ThreadStart ts = new ThreadStart(ar.ProcessRequest);
	    Thread t = new Thread(ts);
	    t.Start();
	    return reqState;
	  }
        
	  public void EndProcessRequest(IAsyncResult ar)
	  {
	    AsyncEditorTemplateState ars = ar as AsyncEditorTemplateState;
	    if (ars != null)
	    {
	     // Clean Up
	    }
	  }      
      
	}
	
	public class AsyncEditorTemplateState : IAsyncResult {
		
		internal HttpContext _ctx;
		internal AsyncCallback _cb;
		internal object _dati;
		private bool _iscompleted = false;
		private ManualResetEvent _callCompleteEvent = null;
		
		public AsyncEditorTemplateState(HttpContext ctx, AsyncCallback cb, object dati) {
			_ctx = ctx;
			_cb = cb;
			_dati = dati;
			
		}
		internal void CompleteRequest() {
			_iscompleted = true;
			lock(this) {
				if(_callCompleteEvent!=null) {
					_callCompleteEvent.Set();
				}
				 if (_cb != null)
				 	_cb(this);
			}
		}
		public object AsyncState {
			get { return _dati; }
		}
		public bool CompletedSynchronously {
			get { return false; }
		}
		public bool IsCompleted            {
			get { return _iscompleted; }
		}
		public WaitHandle AsyncWaitHandle {
			get {
				lock(this) {
					if(_callCompleteEvent == null) 
						_callCompleteEvent = new ManualResetEvent(false);
					return _callCompleteEvent;
				}
			}
		}



	}
	class AsyncEditorTemplateRequest
	{
	  private AsyncEditorTemplateState _asyncRequestState;
	
	  public AsyncEditorTemplateRequest(AsyncEditorTemplateState ars)
	  {
	    _asyncRequestState = ars;
	  }
	    
	  public void ProcessRequest()
	  {
	  	const string baseEditorTemplate = "/editor/template/";
	  	/*
			var tinyMCETemplateList = [
				// Name, URL, Description
				["Simple snippet", "templates/snippet1.htm", "Simple HTML snippet."],
				["Layout", "templates/layout1.htm", "HTML Layout."]
			];
	  	 */
	  	string path = "";
	  	string currentTemplate = ACM.cmsarea08.mainconfiguration.MainConf.CurrentMasterTemplate;
	  	string fileList = string.Empty;
	  	const string tinyResponse = "var tinyMCETemplateList = [{0}];";
	  	const string tinyTemplate = "[\"{0}\", \"{1}\", \"{2}\"] ";
       	System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(_asyncRequestState._ctx.Server.MapPath(currentTemplate+baseEditorTemplate));
       	
       	if(di.Exists) 
		{
       		System.IO.FileInfo[] fis = di.GetFiles("*.htm*");
       		if(fis.Length>0)  {
       			for(int i = 0;i<fis.Length;i++) {
       				fileList += string.Format(tinyTemplate, System.IO.Path.GetFileNameWithoutExtension(fis[i].Name),
       				                          currentTemplate + baseEditorTemplate+ fis[i].Name,
       				                          System.IO.Path.GetFileNameWithoutExtension(fis[i].Name) ) ;
       				if(i<fis.Length-1)
       					fileList+=",";
       			}	
       		}
       	} else fileList = string.Empty;
       	
       	if(fileList==string.Empty) {
			di = new System.IO.DirectoryInfo(_asyncRequestState._ctx.Server.MapPath("/public/"+baseEditorTemplate));       		
			if(di.Exists) {
	       		System.IO.FileInfo[] fis = di.GetFiles("*.htm*");
	    		if(fis.Length>0)  {
	   			for(int i = 0;i<fis.Length;i++) {
	   				fileList += string.Format(tinyTemplate, System.IO.Path.GetFileNameWithoutExtension(fis[i].Name),
	   				                          "/public/" + baseEditorTemplate+ fis[i].Name,
	   				                          System.IO.Path.GetFileNameWithoutExtension(fis[i].Name) ) ;
	   				if(i<fis.Length-1)
	   					fileList+=",";
	   				}	
	   			} 
			}
       	}
       	
 		_asyncRequestState._ctx.Response.ContentType = "text/html";
 		_asyncRequestState._ctx.Response.Write( string.Format(tinyResponse,fileList) );
		//finito.
			
	    _asyncRequestState.CompleteRequest();
	  }
	}
	
}
